/* 
* Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd. 
* SPDX-License-Identifier: MulanPSL-2.0 
*/ 
import React, { useEffect, useState, useRef } from 'react'

import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
import 'codemirror/keymap/sublime'
import 'codemirror/mode/shell/shell'
import { Controlled as CodeMirror } from 'react-codemirror2'
import styles from './index.less'

export default ({ code , onChange, readOnly= true, lineNumbers= false, height = 372, theme, mode='shell', domId= 'code_wrapper' } : any ) => {
    const [statusCode, setStatusCode] = useState('')
    const codemirrorRef: any = useRef({});

    useEffect(()=> {
      // 延迟渲染内容
      const t = setTimeout(()=> {
        setStatusCode(code)
      }, 100)
      return ()=> {
        t && clearTimeout(t)
      }
    }, [code])

    useEffect(()=> {
      if (codemirrorRef?.current) {
        const { editor } : any = codemirrorRef?.current || {}
        const { display = {}} = editor || {}
        const { wrapper = {}} = display || {}
        const { style = {}} = wrapper || {}
        style.height = height + 'px';
      }
    }, [codemirrorRef, height])

    return (
      <div id={domId}>
        <CodeMirror
          ref={codemirrorRef}
          value={ statusCode }
          className={ styles.code_wrapper}
          options={{
              theme: theme || 'monokai',
              keyMap: 'sublime',
              mode,
              lineWrapping: true,
              lineNumbers: lineNumbers,
              readOnly: readOnly,
          }}
          onBeforeChange={( editor: any , data: any , value: any ) => onChange( value )}
        />
      </div>
    )
}